package com.example.hackercore.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.entity.UrlEncodedFormEntity;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.swing.text.html.parser.Entity;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.Map;

/**
 * Description：
 *
 * @Author: cw
 * CreateTime：2022-10-13
 */
public class HttpUtil {

    private static final Logger log = LoggerFactory.getLogger(HttpUtil.class);

    public static String doGet(String url, Map<String,Object> param){
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        try{

            HttpGet get = new HttpGet(url);
            response = httpClient.execute(get);

            if(response.getCode() == HttpURLConnection.HTTP_OK){
                return EntityUtils.toString(response.getEntity());
            }

        } catch (Exception e) {
            log.error("get请求失败",e);
        } finally {
            if(null != response){
                try {
                    response.close();
                } catch (IOException e) {
                    log.error("get请求流关闭错误",e);
                }
            }
        }
        return null;

    }



    public static String doPost(String url , String param){
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        try{
            HttpPost post = new HttpPost(url);
            post.setEntity(new StringEntity(param, ContentType.APPLICATION_JSON));

            response = httpClient.execute(post);

            if(response.getCode() == HttpURLConnection.HTTP_OK){
                return EntityUtils.toString(response.getEntity());
            }

        } catch (Exception e) {
            log.error("post请求错误",e);
        } finally {
            if(null != response) {
                try {
                    response.close();
                } catch (IOException e) {
                    log.error("post请求流关闭错误",e);
                }
            }
        }
        return null;
    }

}
